package com.jingbian.cppccbackend.controller.user;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jingbian.cppccbackend.entity.*;
import com.jingbian.cppccbackend.entity.dto.ChangePasswordDTO;
import com.jingbian.cppccbackend.entity.dto.UserDTO;
import com.jingbian.cppccbackend.service.admin.HomePageBannerService;
import com.jingbian.cppccbackend.service.admin.HomePageNotificationsService;
import com.jingbian.cppccbackend.service.admin.NewsService;
import com.jingbian.cppccbackend.service.user.UsersService;
import com.jingbian.cppccbackend.utils.JwtUtil;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-09
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    
    @Autowired
    private UsersService usersService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private HomePageBannerService homePageBannerService;
    @Autowired
    private HomePageNotificationsService notificationsService;
    @Autowired
    private NewsService newsService;


    //查看用户信息
    @GetMapping("/getUserInfo")
    public Result<Users> getUserInfo() {
        //由于用户登录的时候，它的账号是电话，所以在用户登录的逻辑要先把数据放入到ThreadLocal中，
        // 参考管理员登录的写法，添加claims.put（）方法，把登录时的账号（即电话，可以作为身份的唯一识别）存储起来
        Map<String, Object> map = ThreadLocalUtil.get();
        //这里就可以从存储数据中获取到电话的信息
        String phone=(String)map.get("phone");
        //根据电话去查用户的数据信息
        Users user = usersService.getUserInfo(phone);
        if (user != null) {
            return ResultUtil.success(user);
        }
        return ResultUtil.fail("用户不存在");
    }

    /**
     * 微信用户--账号密码登录
     * @param phone
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestParam String phone, @RequestParam String password) {
        Users user = usersService.getUserInfo(phone);
        if(user== null){
            return ResultUtil.fail("该手机号尚未注册，请先注册");
        }
        if (user != null && user.getPassword().equals(password)) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("uid", user.getUid());
            claims.put("phone", user.getPhone());  // 用于区分是用户token
            // 设置token过期时间为30天
            String token = JwtUtil.genToken(claims);

            //存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 30, TimeUnit.DAYS);
            if(user.getStatus().equals("已驳回")){
                return ResultUtil.fail("审核不通过，请重新注册！");
            }
            if(user.getStatus().equals("已注销")){
                return ResultUtil.fail("该账号已注销，请联系管理员！");
            }
            if(user.getStatus().equals("未处理")){
                return ResultUtil.fail("账号正在审核中！");
            }
            return ResultUtil.success(token);
        }
        return ResultUtil.fail("手机号或密码错误");
    }


    /**
     * 用户进行微信小程序用户账号的注册
     * @param userDTO
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO userDTO) {
        boolean register = usersService.add(userDTO);
        if (register) {
            return ResultUtil.success("注册成功！");
        }
        return ResultUtil.fail("注册失败！该手机号已注册！");
    }


    /**
     * 获取微信用户--手机号
     * @param code
     * @return
     */
    @PostMapping("/getPhoneNumber")
    public Result getPhoneNumber(@RequestParam String code) {
        // 1. 获取access_token（需补充缓存机制）
        WechatConstant wechatConstant = new WechatConstant();
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
            wechatConstant.getAppid(), wechatConstant.getSecret());
        JSONObject token = JSON.parseObject(HttpUtil.get(tokenUrl));

        // 2. 构建请求参数
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token.getString("access_token");

        // 3. 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON); // 关键顺序

        // 4. 手动序列化为JSON字符串
        String jsonBody = JSON.toJSONString(Collections.singletonMap("code", code));
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonBody, headers);

        // 5. 发送请求
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);
        System.out.println(response.getBody());
        return ResultUtil.success(response.getBody());
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @PostMapping("/wxLogin")
    public Result wxLogin(@RequestParam String code) {
        Users users = usersService.wxLogin(code);
        if (users != null) {
           Map<String, Object> claims = new HashMap<>();
           claims.put("uid", users.getUid());
           claims.put("phone", users.getPhone());  // 用于区分是用户token
           // 设置token过期时间为30天
           String token = JwtUtil.genToken(claims);
            //存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 30, TimeUnit.DAYS);
            if(users.getStatus().equals("未处理")){
                return ResultUtil.fail("账号注册中，待审核！");
            }
            else if (users.getStatus().equals("已驳回")){
                return ResultUtil.fail("审核不通过，请重新注册！");
            }
            return ResultUtil.success(token);
        }
        return ResultUtil.fail("该微信号尚未注册，请先注册！");
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/changePassword")
    public Result<String> changePassword(@RequestBody ChangePasswordDTO changePasswordDTO) {
       int n =usersService.updateUsers(changePasswordDTO);
       if(n == 1){
           return ResultUtil.success("密码修改成功！");
       } else if(n == 0){
           return ResultUtil.fail("原密码错误！");
       } else {
            return ResultUtil.fail("密码修改失败！");
       }
    }


    /**
     * 获取所有轮播图列表
     */
    @GetMapping("/banners/list")
    public Result<List<HomePageBanner>> getAllBanners() {
        List<HomePageBanner> banners = homePageBannerService.list();
        return ResultUtil.success(banners);
    }

    /**
     * 获取所有通知列表
     */
    @GetMapping("/notifications/list")
    public Result<List<HomePageNotifications>> getNotificationsList() {
        List<HomePageNotifications> list = notificationsService.list();
        return ResultUtil.success(list);
    }

    /**
     * 获取新闻通知列表
     */
    @GetMapping("/news/list")
    public Result<List<News>> getNewsList() {
        // 创建查询条件
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        // 按创建时间降序排序
        queryWrapper.orderByDesc(News::getCreatedAt)  
                    .last("LIMIT 4");  // 限制返回5条记录
        
        List<News> news = newsService.list(queryWrapper);
        return ResultUtil.success(news);
    }
}
